<?php
namespace app\api\common;
use app\common\model\UserCirclePrice as UserCirclePriceModel;
use app\common\model\Config as ConfigModel;
use app\common\model\User as UserModel;
use think\Db;
class WxPay
{
    protected $apiclient_key;

    //统一下单
    public function wxpay(int $user_id,string $order_no,$notify_url="",string $description='商品描述')
    {
        if (!function_exists('\sodium_crypto_aead_aes256gcm_is_available')){
            return ['code'=>201,'msg'=>'php环境未开启sodium_crypto_aead_aes256gcm_is_available函数'];
        }
        $wx_appid = ConfigModel::getConfigValue("wx_appid");//appid
        $wx_mchid = ConfigModel::getConfigValue("wx_mchid");//商户ID
        $wx_pay_xlid = ConfigModel::getConfigValue("wx_pay_xlid");//证书序列号
        $wx_pay_apiclient_key = ConfigModel::getConfigValue("wx_pay_apiclient_key");//微信支付apiv3证书内容
        $this->apiclient_key = $wx_pay_apiclient_key;
        $Initial = substr($order_no,0,1);
        if ($Initial=='F'){ //发帖支付
            $order_info = UserCirclePriceModel::where('order_no',$order_no)->find();
        }elseif ($Initial=='Z'){ //置顶帖子支付
            $order_info = UserCirclePriceModel::where('order_no',$order_no)->find();
        }elseif ($Initial=='B'){ //商家保证金支付
            $order_info = Db::name("user_deposit")->where('order_no',$order_no)->find();
        }elseif ($Initial=='L'){ //群聊保证金支付
            $order_info = Db::name("chat_group_user")->where('order_no',$order_no)->find();
        }elseif ($Initial=='R'){ //商家认证费支付
            $order_info = Db::name("user_certification")->where('order_no',$order_no)->find();
        }elseif ($Initial=='X'){ //商家认续费支付
            $order_info = Db::name("user_certification")->where('order_no',$order_no)->find();
        }
        if (empty($order_info)){
            return ['code'=>201,'msg'=>'订单不存在'];
        }
        $total = intval(bcmul($order_info['price'],100,0));
        $user_info = UserModel::find($user_id);
        $openid = $user_info->open_id;
        // 官方提供网址
        $url = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $time = (string)time(); //时间戳
        $noncestr = $this->getNonceStr();
        $appid = $wx_appid;//appID
        $mchid = $wx_mchid;//商户ID
        $xlid = $wx_pay_xlid;//证书序列号
        $data = array();
        $data['appid'] = $appid;
        $data['mchid'] = $mchid;
        $data['description'] = $description;//商品描述
        $data['out_trade_no'] = $order_no;//订单编号，订单号在微信支付里是唯一的
        $data['notify_url'] = $notify_url;//需根据自己的情况修改回调接口，也可以为空
        $data['amount']['total'] = $total;//金额 单位 分
//        $data['amount']['total'] = 1;//金额 单位 分
        $data['scene_info']['payer_client_ip'] = $_SERVER["REMOTE_ADDR"];;//场景ip
        $data['payer']['openid']=$openid; //openid
        $data = json_encode($data);
        //签名，包含了$data数据、微信指定地址、随机数和时间
        $key = $this->getSign($data,$urlarr['path'],$noncestr,$time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$noncestr,$time,$key);
        //头部信息
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
        );
        //向微信接口地址提交json格式的$data和header的头部信息，得到返回值
        $res = json_decode($this->curl_post_https($url,$data,$header),true);
        if (empty($res['prepay_id'])){
            return ['code'=>201,'msg'=>$res['message']];
        }
        $prepay_id=$res['prepay_id'];
        $paySign=$this->getWechartSign($appid,$time,$noncestr,'prepay_id='.$prepay_id);
        $payData=[
            'order_no'=>$order_no,
            'appid'=>$appid,
            'noncestr'=>$noncestr,
            'package'=>"prepay_id=$prepay_id",
            'partnerid'=>$mchid,
            'prepayid'=>$prepay_id,
            'timestamp'=>$time,
            'sign'=>$paySign,
            'signType'=>'RSA',
        ];
        return ['code'=>200,'msg'=>'ok','data'=>$payData];
    }

    //退款
    public function Refund($transaction_id,$order_no,$refund,$total,$reason){ //商户订单号,微信生成的退款订单号 二选一即可
        $time=time();
//        $refund = 1;
//        $total = 1;
        $refund=$refund*100;
        $total=$total*100;
        (int) $_SERVER['SERVER_PORT']==80?$protocol_name = 'http://':$protocol_name = 'https://';
        $refundData=[
            'out_refund_no'=>$order_no,
            'transaction_id'=>$transaction_id,
            'reason'=>$reason,
            'notify_url'=> $protocol_name.$_SERVER['SERVER_NAME'].'/api/Notify/refund_notify',
            'funds_account'=>'AVAILABLE',
            'amount'=>[
                'refund'=>(int) $refund, //退款标价金额，单位为分，可以做部分退款
                'total'=>(int) $total, //订单总金额，单位为分
                'currency'=>'CNY'
            ]
        ];
        write_log($refund);
        write_log($total);
        write_log($refundData['amount']['refund']);
        $wx_mchid = ConfigModel::getConfigValue("wx_mchid");//商户ID
        $wx_pay_xlid = ConfigModel::getConfigValue("wx_pay_xlid");//证书序列号
        $wx_pay_apiclient_key = ConfigModel::getConfigValue("wx_pay_apiclient_key");//微信支付apiv3证书内容
        $this->apiclient_key = $wx_pay_apiclient_key;
        $url='https://api.mch.weixin.qq.com/v3/refund/domestic/refunds';
        $urlarr = parse_url($url); //拆解为：[scheme=>https,host=>api.mch.weixin.qq.com,path=>/v3/pay/transactions/native]
        $mchid = $wx_mchid;//商户ID
        $xlid = $wx_pay_xlid;//证书序列号
        $refundData=json_encode($refundData);
        $nonce = $this->getNonceStr();
        $key = $this->getSign($refundData,$urlarr['path'],$nonce,$time);
        $token = sprintf('mchid="%s",serial_no="%s",nonce_str="%s",timestamp="%d",signature="%s"',$mchid,$xlid,$nonce,$time,$key);
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'User-Agent:*/*',
            'Authorization: WECHATPAY2-SHA256-RSA2048 '.$token
        );
        $res=$this->curl_post_https($url,$refundData,$header);
        $res_array=json_decode($res,true);
        // var_dump($res_array);die;
        write_log($res_array);
        if(isset($res_array['status']))
        {
            if(($res_array['status']=='PROCESSING' || $res_array['status']=='SUCCESS') && isset($res_array['status'])){
                return ['code'=>1,'msg'=>'退款成功'];
            }else{
                return ['code'=>0,'msg'=>$res_array['message']];
            }
        }
        else
        {
            return ['code'=>0,'msg'=>$res_array['message']];

        }
        
    }

    //获取随机字符串
    public function getNonceStr(){
        $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        $name=substr(str_shuffle($strs),mt_rand(0,strlen($strs)-11),32);
        return $name;
    }

    //微信支付签名
    function getSign($data,$url,$randstr,$time){
        $str = "POST"."\n".$url."\n".$time."\n".$randstr."\n".$data."\n";
//        $key = file_get_contents('apiclient_key.pem');//在商户平台下载的秘钥,读取到变量
        $key = $this->apiclient_key;
        $str = $this->getSha256WithRSA($str,$key);
        return $str;
    }

    //调起支付的签名
    function getWechartSign($appid,$timeStamp,$noncestr,$prepay_id){
        $str = $appid."\n".$timeStamp."\n".$noncestr."\n".$prepay_id."\n";
//        $key = file_get_contents('apiclient_key.pem');//在商户平台下载的秘钥,读取到变量
        $key = $this->apiclient_key;
        $str = $this->getSha256WithRSA($str,$key);
        return $str;
    }

    //加密
    public function getSha256WithRSA($content, $privateKey){
        $binary_signature = "";
        $algo = "SHA256";
        openssl_sign($content, $binary_signature, $privateKey, $algo);
        $sign = base64_encode($binary_signature);
        return $sign;
    }

    /* PHP CURL HTTPS POST */
    public function curl_post_https($url,$data,$header){ // 模拟提交数据函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在，如果出错则修改为0，默认为1
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }


}